<template>
    <div>
        <label v-if="label">{{label}}</label>
        <slot></slot>
        <div v-if="error" style="color: red">{{error}}</div>
    </div>
</template>

<script>
    import Schema from 'async-validator';
    export default {
        name: "KFormItem",
        inject:{
            dataRules: "rules",
            model: "model"
        },
        props:{
            label:{
                type: String,
                default: ""
            },
            prop:{
                type: String,
                default: ""
            }
        },
        data() {
            return {
                error: ""
            }
        },
        mounted() {
            // 这里接收子组件派发的事件
            this.$on("validate", () => {
                this.validate()
            })
        },
        methods: {
            validate() {
                const rule = this.dataRules[this.prop]
                const value = this.model[this.prop]
                const validator = new Schema({ [this.prop]: rule});
                return validator.validate({ [this.prop]: value }, (errors) => {
                    if (errors) {
                        this.error = errors[0].message;
                    }else{
                        this.error = ""
                    }
                });
            }
        },
    }
</script>

<style scoped>

</style>
